package com.de2;

public class BinarySearch {

    public static void main(String[] args) {
        int[] a = {1,2,2,2,3};
        System.out.println(upperBound(a,2));
        System.out.println(downBound(a,2));
        System.out.println("2的个数有"+ (upperBound(a,2) - downBound(a,2) + 1));
    }


    //求下界
    public static int downBound(int[] a,int t){
        int left = 0;
        int right = a.length - 1;
        while (left < right){
            int mid = ( left + right ) / 2;
            if (a[mid] >= t){
                right = mid;
            }else {
                left = mid + 1;
            }
        }
        return left;
    }

    // 求上界
    public static int upperBound(int[] a,int t){
        int left = 0;
        int right = a.length - 1;
        while (left < right){
            int mid = (left + right + 1) / 2;  // /是向下取整的，不+1会陷入死循环
            if (a[mid] <= t){
                left = mid;
            }else {
                right = mid - 1;
            }
        }
        return left;
    }
}
